package cn.lzd.mr.case5;

import cn.lzd.mr.PathUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by lzd on 2018/6/1.
 * 分组topn的简单实现
 */
public class Case5MR {
    static class Mp extends Mapper<LongWritable, Text, Case5Bean, NullWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split(",");
            Case5Bean bean = new Case5Bean(split[0], split[1], split[2], Float.parseFloat(split[3]), Integer.parseInt(split[4]));
            context.write(bean, NullWritable.get());
        }
    }

    static class Rd extends Reducer<Case5Bean, NullWritable, Case5Bean, NullWritable> {

        @Override
        protected void reduce(Case5Bean key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
            int count = context.getConfiguration().getInt("top.n", 1);
            int i = 0;
            for (NullWritable value : values) {
                context.write(key, value);
                if ((++i) == count) {
                    return;
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration = new Configuration();
        configuration.setInt("top.n", 3);
        Job job = Job.getInstance(configuration);
        job.setJarByClass(Case5MR.class);

        job.setOutputKeyClass(Case5Bean.class);
        job.setOutputValueClass(NullWritable.class);

        job.setMapOutputKeyClass(Case5Bean.class);
        job.setMapOutputValueClass(NullWritable.class);

        job.setMapperClass(Mp.class);
        job.setReducerClass(Rd.class);
//        job.setPartitionerClass(Case5Partition.class);
        job.setGroupingComparatorClass(Case5Group.class);

        FileInputFormat.setInputPaths(job, new Path(PathUtil.getpath("case4") + "text"));
        FileOutputFormat.setOutputPath(job, new Path(PathUtil.getpath("case4") + "out/"));

        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
}